package leetcode.test;

import java.util.concurrent.TimeUnit;

/**
 * @author :songyaozhang
 * @date :Created 2021/8/3 16:57
 * @description :死锁
 */
public class DeadLock {

    public static void main(String[] args) {
        new Fetch(0, "张三").start();
        new Fetch(1, "李四").start();

    }

}
class A {}
class B {}

class Fetch extends Thread {
    static private A a = new A();
    static private B b = new B();

    int choice;
    String name;

    public Fetch(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        super.run();
        fetch();
    }

    private void fetch() {
        if (choice == 0) {
            synchronized (a) {
                System.out.println(name + " " + "a");
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b) {
                    System.out.println(name + " " + "b");
                }
            }
        } else {
            synchronized (b) {
                System.out.println(name + " " + "b");
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (a) {
                    System.out.println(name + " " + "a");
                }
            }
        }
    }
}
